package cn.initcap.authentication;

import cn.initcap.common.JsonData;
import cn.initcap.properties.LoginResponseType;
import cn.initcap.properties.SecurityProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

/**
 * 登录失败处理器
 *
 * @author initcap
 * @date Created in 2018/5/17 PM10:53.
 */
@Slf4j
@Component("initcapAuthenticationFailureHandler")
public class InitcapAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException e) throws IOException, ServletException {

        log.info("登录失败");

        if (LoginResponseType.JSON.equals(securityProperties.getWeb().getSignInResponseType())) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(JsonData.fail(e.getMessage())));
        } else {
            super.onAuthenticationFailure(request, response, e);
        }

    }
}
